<template>
  <a-card
    class="general-card"
    :bordered="false"
    title="物流公司"
  >
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary" @click="handleAdd">
            添加
          </a-button>
        </a-space>
      </a-col>
    </a-row>
    <PickTablePage
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :api="getLogistics"
      @delete="handleDelete"
      @editor="handleEdit"
      :bordered="true"
    >
      <template #btnList="{ data }">
        <a-space size="large">
          <a-switch
            v-model="data.disabled"
            checked-value="OPEN"
            unchecked-value="CLOSE"
            @change="logisticsChange(data)"
          >
            <template #checked> 启用 </template>
            <template #unchecked> 禁用 </template>
          </a-switch>
        </a-space>
      </template>
    </PickTablePage>
    <!-- 添加/编辑modal -->
    <a-modal
      v-model:visible="logisticsData.enableAddModal"
      :align-center="false"
      :footer="false"
    >
      <template #title> {{ title }} </template>
      <a-form ref="formRef" :model="logisticsData.form" auto-label-width @submit="handleAddOk">
        <a-form-item
          field="name"
          label="物流公司名称"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="logisticsData.form.name" />
        </a-form-item>
        <a-form-item
          field="code"
          label="物流公司代码"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="logisticsData.form.code" />
        </a-form-item>

        <a-form-item label="支持电子面单" field="deleteFlag">
          <a-switch
            v-model="logisticsData.form.standBy"
            checked-value="OPEN"
            unchecked-value="CLOSE"
          >
            <template #checked> 开 </template>
            <template #unchecked> 关 </template>
          </a-switch>
        </a-form-item>
        <a-form-item
          field="formItems"
          label="电子面单表单"
          :validate-trigger="['change']"
        >
          <a-input v-model="logisticsData.form.formItems" />
        </a-form-item>
        <a-form-item field="disabled" label="启用状态">
          <a-switch
            v-model="logisticsData.form.disabled"
            unchecked-color="#515A6E"
            checked-value="OPEN"
            unchecked-value="CLOSE"
          >
            <template #checked> 开 </template>
            <template #unchecked> 关 </template>
          </a-switch>
        </a-form-item>
        <a-form-item label="操作">
          <a-button :loading="logisticsData.formLoading" html-type="submit"
          type="primary">保存</a-button
          >
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import { PickTablePage } from '@pickmall/ui-v3-components'  
  import { MethodsRule, ColumnsDataRule } from '@/types/global';
  import {
    getLogistics,
    delLogistics,
    addLogistics,
    updateLogistics,
  } from '@/api/logistics';
  import { REQUIRED, VARCHAR20 } from '@/utils/validator';
  import { ref, reactive } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import useCurrentInstance from '@/hooks/useCurrentInstance';

  const tablePageRef = ref<any>();
  const title = ref<string>('');
  const formRef = ref<FormInstance>();
  interface formInterface {
    enableAddModal: boolean;
    formLoading: boolean;
    fid: string | number;
    form: {
      name: string;
      code: string;
      disabled: string;
      standBy: string;
      formItems: string;
      [key: string]: any;
    };
    [key: string]: any;
  }
  // 获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const columnsTable: ColumnsDataRule[] = [
    {
      title: '物流公司名称',
      dataIndex: 'name',
      width: 300,
    },
    {
      title: '物流公司编码',
      dataIndex: 'code',
    },
    {
      title: '状态',
      dataIndex: 'btnList',
      slot: true,
      slotTemplate: 'btnList',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 300,
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 300,
    methods: [
      {
        title: '修改',
        callback: 'editor',
        type:'text',
        status:'warning'
      },
      {
        title: '删除',
        callback: 'delete',
        type:'text',
        status:'danger'
      },
    ],
  };

  // 数据集
  const logisticsData = reactive<formInterface>({
    enableAddModal: false,
    formLoading: false,
    fid: '', // 当前form的ids
    form: {
      name: '',
      code: '',
      disabled: '',
      standBy: '',
      formItems: '',
    }, // 表单提交数据
  });
  // 状态状态改变事件
  const logisticsChange = (val: any) => {
    if (val) {
      Object.keys(val).forEach((key) => {
        // eslint-disable-next-line no-unused-expressions,no-prototype-builtins
        logisticsData.form.hasOwnProperty(key)
          ? (logisticsData.form[key] = val[key])
          : '';
      });
      logisticsData.fid = val.id;
      val.disabled == 'CLOSE'
        ? logisticsData.form.disabled == 'OPEN'
        : logisticsData.form.disabled == 'CLOSE';
      updateLogistics(logisticsData.fid, logisticsData.form).then(
        (res: any) => {
          console.log(res);
        }
      );
    }
  };
  // 点击添加
  function handleAdd() {
    logisticsData.enableAddModal = true;
    title.value = '添加';
    logisticsData.fid = '';
    Object.keys(logisticsData.form).forEach((key) => {
      logisticsData.form[key] = '';
    });
  }
  // 添加/修改
  async function handleAddOk() {
    // logisticsData.form.password = this.md5(logisticsData.form.password);
    const auth = await formRef.value?.validate();
    if (!auth) {
      let res;
      !logisticsData.fid
        ? (res = await addLogistics(logisticsData.form))
        : (res = await updateLogistics(logisticsData.fid, logisticsData.form));

      if (res.data.success) {
        Message.success(`${logisticsData.fid ? '修改' : '添加'}成功!`);
        logisticsData.enableAddModal = false;
        tablePageRef.value.init();
      }
    }
  }
  // 点击修改地址
  function handleEdit(val: any) {
    title.value = '编辑';
    if (val) {
      Object.keys(val.record).forEach((key) => {
        // eslint-disable-next-line no-unused-expressions,no-prototype-builtins
        logisticsData.form.hasOwnProperty(key)
          ? (logisticsData.form[key] = val.record[key])
          : '';
      });
      logisticsData.fid = val.record.id;
      logisticsData.enableAddModal = true;
    }
  }
  // 回调删除
  function handleDelete(data: any) {
    modal.confirm({
      title: '确认删除',
      content: `您确认要删除么?`,
      alignCenter: false,
      onOk: async () => {
        const res = await delLogistics(data.record.id);
        if (res.data.success) {
          Message.success('删除成功');
          tablePageRef.value.init();
        }
      },
    });
  }
</script>
